package com.atguigu.day07;

import com.atguigu.utils.OrderEvent;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.util.Collector;

// 流A：app的支付信息流
// 流B：weixin的支付信息流
public class Example7 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<OrderEvent> appZhifuStream = env
                .addSource(new SourceFunction<OrderEvent>() {
                    @Override
                    public void run(SourceContext<OrderEvent> ctx) throws Exception {
                        OrderEvent e1 = new OrderEvent("order-1", "app-zhifu", 1000L);
                        // 发送e1事件，同时指定e1的事件时间是e1.ts
                        ctx.collectWithTimestamp(e1, e1.ts);
                        Thread.sleep(1000L);
                        OrderEvent e2 = new OrderEvent("order-2", "app-zhifu", 2000L);
                        ctx.collectWithTimestamp(e2, e2.ts);
                        Thread.sleep(1000L);
                        // 发送了一条7000毫秒的水位线
                        ctx.emitWatermark(new Watermark(7000L));
                        Thread.sleep(1000L);
                    }

                    @Override
                    public void cancel() {

                    }
                });

        SingleOutputStreamOperator<OrderEvent> weixinZhifuStream = env
                .addSource(new SourceFunction<OrderEvent>() {
                    @Override
                    public void run(SourceContext<OrderEvent> ctx) throws Exception {
                        OrderEvent e1 = new OrderEvent("order-1", "weixin-zhifu", 4000L);
                        ctx.collectWithTimestamp(e1, e1.ts);
                        Thread.sleep(1000L);
                        // 发送7000毫秒的水位线
                        ctx.emitWatermark(new Watermark(7000L));
                        Thread.sleep(1000L);
                        OrderEvent e2 = new OrderEvent("order-2", "weixin-zhifu", 9000L);
                        ctx.collectWithTimestamp(e2, e2.ts);
                        Thread.sleep(1000L);
                    }

                    @Override
                    public void cancel() {

                    }
                });

        appZhifuStream.keyBy(r -> r.orderId)
                .connect(weixinZhifuStream.keyBy(r -> r.orderId))
                .process(new Match())
                .print();

        env.execute();
    }

    // 如果app的支付信息先到达，那么保存到appState，然后等待weixin支付5秒钟，如果5秒钟之内，weixin支付未到达，那么输出对账失败信息
    // 如果weixin的支付信息先到达，那么保存到weixinState，然后等待app支付5秒钟，如果5秒钟之内，app支付未到达，那么输出对账失败信息
    public static class Match extends
            CoProcessFunction<OrderEvent, OrderEvent, String> {
        private ValueState<OrderEvent> appState;
        private ValueState<OrderEvent> weixinState;
        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            appState = getRuntimeContext().getState(
                    new ValueStateDescriptor<OrderEvent>(
                            "app-state",
                            Types.POJO(OrderEvent.class)
                    )
            );
            weixinState = getRuntimeContext().getState(
                    new ValueStateDescriptor<OrderEvent>(
                            "weixin-state",
                            Types.POJO(OrderEvent.class)
                    )
            );
        }

        // 处理的是app-zhifu
        @Override
        public void processElement1(OrderEvent value, Context ctx, Collector<String> out) throws Exception {
            if (weixinState.value() == null) {
                // app支付先到达，保存下来
                // 因为如果weixin先到达的话，会保存在weixinState中
                appState.update(value);
                // 注册5秒钟之后的定时器
                ctx
                        .timerService()
                        .registerEventTimeTimer(value.ts + 5000L);
            } else {
                // weixin-zhifu先到达，因为weixinState里面有数据
                // 直接输出对账成功的信息，不保存app-zhifu
                out.collect("订单" + value.orderId + "对账成功" +
                        "" + "weixin支付先到达");
                // 对账成功，清空weixinState
                weixinState.clear();
            }
        }

        @Override
        public void processElement2(OrderEvent value, Context ctx, Collector<String> out) throws Exception {
            if (appState.value() == null) {
                weixinState.update(value);
                ctx
                        .timerService()
                        .registerEventTimeTimer(value.ts + 5000L);
            } else {
                out.collect("订单" + value.orderId + "对账成功" +
                        "" + "app支付先到达");
                // 对账成功后，要清空appState
                appState.clear();
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            if (appState.value() != null) {
                // app-zhifu先到达，并且当定时器触发时，weixin-zhifu还没到
                out.collect("订单" + appState.value().orderId + "对账失败，" +
                        "weixin支付没来");
                appState.clear();
            }
            if (weixinState.value() != null) {
                out.collect("订单" + weixinState.value().orderId + "对账失败，" +
                        "app支付没来");
                weixinState.clear();
            }
        }
    }
}
